<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\admin\controller\v1;
use app\admin\Adminbase;

class CouponUser extends Adminbase 
{
	
	/**
	* 删除
	* /admin/v1/coupon_user/del
	* 需要登录 
	* @is_need_login true
	*/
	public function del($coupon_id,$ids='',$data = '[]'){
		if((!$ids && $data=='[]') || !$coupon_id){
			return $this ->  ReError("参数错误");
		}
		
		try {
			
			if($ids){
				$result = model('CouponUser')->where('id',$ids)->delete();
				$num =  count(explode(',',$ids));
				$result = $result && model('CouponIssue')->replyNum($coupon_id,$num);
			}else{
				$datas = json_decode($data,true);
				foreach ($datas as $key => $item) {
					if( $item['is_temp'] ==1){
						$result = model('CouponUserTemp')->where('id',$item['id'])->delete();
					}else{
						$result = model('CouponUser')->where('id',$item['id'])->delete();
					}
				}
				$result = $result && model('CouponIssue')->replyNum($coupon_id, count($datas));
			}
			
			if($result !== true){
				return $this->ReError( '异常错误' );	
			}else{
				return $this->ReSucess(true);	
			}
			
			return $this->ReSucess(true);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 设置数量
	* /admin/v1/coupon_issue/setNum
	* 需要登录 
	* @is_need_login true
	*/
	public function setNum($id,$add_num=0,$reduce_num=0){
		try { 
			$model =  model('CouponIssue');
			$result =  $model->setTotalNum($id,$add_num,$reduce_num);
			if($result !== true){
				return $this->ReError( $model->errorInfo );	
			}else{
				return $this->ReSucess(true);	
			}
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}

	/**
	* 通过用户id来获取发放优惠券数
	* /admin/v1/coupon_user/getcoupon
	* 需要登录 
	* @is_need_login true
	*/
	public function getcoupon($uid){
        $request =  request();

		try {
			$model = model('CouponUser');
			$result =$model->where('uid',$uid)->select();

			if($result){
                return $request->isAjax() ? $this->ReSucess($result) : $result;

			}else{
                return $this->ReError($result);

			}
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());
		}
	}
	
	
}

